package cn.admin.config.common.protocol;

import com.caucho.hessian.io.AbstractSerializerFactory;
import com.caucho.hessian.io.Deserializer;
import com.caucho.hessian.io.HessianProtocolException;
import com.caucho.hessian.io.Serializer;

import java.util.HashMap;
import java.util.Map;

public class ProtocolPacketCodec extends AbstractSerializerFactory {

    private ProtocolPacketEncoder encoder = new ProtocolPacketEncoder();
    private Map<Class<?>,ProtocolPacketDecoder> decoders = new HashMap<>();

    @Override
    public Serializer getSerializer(Class cl) throws HessianProtocolException {
        return ProtocolPacket.class.isAssignableFrom(cl) ? this.encoder : null;
    }

    @Override
    public Deserializer getDeserializer(Class cl) throws HessianProtocolException {
        if (!ProtocolPacket.class.isAssignableFrom(cl)) {
            return null;
        } else {
            try {
                synchronized(this) {
                    ProtocolPacketDecoder decoder;
                    decoder = this.decoders.get(cl);
                    if (decoder == null) {
                        decoder = new ProtocolPacketDecoder(cl);
                        this.decoders.put(cl, decoder);
                    }
                    return decoder;
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
                throw e;
            }
        }
    }
}
